//
//  ControllerForClickItem.m
//  ProjectA
//
//  Created by dllo on 16/1/26.
//  Copyright © 2016年 刘旺辉. All rights reserved.
//

#import "ModelForSectionHeader.h"   //M
#import "ModelForClickItem.h"
#import "ModelForSectionFooter.h"
#import "ModelForSection1.h"

#import "ViewForSectionHeader.h"    //V
#import "ViewForSectionFooter.h"
#import "CellForClickItem.h"

#import "ControllerForClickItem.h"  //C

@interface ControllerForClickItem ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *arrForSectionHeader;
@property (nonatomic, strong) NSMutableArray *arrForClickItem;
@property (nonatomic, strong) NSMutableArray *arrForSectionFooter;
@property (nonatomic, strong) UIBarButtonItem *buttonForCollect;
@property (nonatomic, strong) UIButton *button;
@property (nonatomic, assign) BOOL isSave;
@property (nonatomic, strong) UIAlertController *alert;
@end

@implementation ControllerForClickItem
- (void)dealloc {
    
    self.tableView.dataSource = nil;
    self.tableView.delegate = nil;
    
    [_alert release];
    [_button release];
    [_buttonForCollect release];
    [_tableView release];
    [_arrForSectionHeader release];
    [_arrForClickItem release];
    [_arrForSectionFooter release];
    [_model release];
    [_spot_id release];
   
    [super dealloc];
    
}

- (void)setLightDayModel {
    
    [super setLightDayModel];
   // self.navigationController.navigationBar.barTintColor = RGBA(44, 211, 209, 1);
   // [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:L_COLOR_BLACK}];
   // self.navigationItem.leftBarButtonItem.tintColor = L_COLOR_BLACK;
    self.barBackgroundView.backgroundColor = RGBA(44, 211, 209, 1);
}

- (void)setNightDayModel {
    
    [super setNightDayModel];
  //  self.navigationController.navigationBar.barTintColor = L_COLOR_GRAY;
  //  [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:L_COLOR_WHITE}];
  //  self.navigationItem.leftBarButtonItem.tintColor = L_COLOR_WHITE;
    self.barBackgroundView.backgroundColor = RGBA(52, 52, 52, 1);
}
- (void)viewWillAppear:(BOOL)animated {
    [self.tableView reloadData];
    //http://api.breadtrip.com/v2/new_trip/spot/?spot_id=
    
    if ([[DataBaseHandler shareDataBaseHandler] selectForId:self.model.spot_id]) {
        UIImage *image = [UIImage imageNamed:@"iconfont-shoucang"];
        [self.button setBackgroundImage:[image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        self.button.selected = !self.button.selected;
    }
    if (ISNIGHT) {
        [self setNightDayModel];
    } else {
        [self setLightDayModel];
    }
    
}
- (void)viewWillDisappear:(BOOL)animated {
    self.barBackgroundView.backgroundColor = L_COLOR_CLEAR;
}
- (void)viewDidLoad {
    
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    // 加载数据菊花
    [self.view addSubview:[UIViewForActivityIndicator shareActivityIndicatorViewWithFrame:self.view.frame]];
    
    [self handleData];
    [self createTableView];
    [self createAlertController];
    [self settingsNavigationController];
    
}
- (void)createAlertController {
    
    self.alert = [UIAlertController alertControllerWithTitle:@"收藏成功" message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"确定" style:0 handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [self.alert addAction:alertAction];
                                  
}
                                  
- (void)settingsNavigationController {

    self.navigationItem.title = @"故事详情";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-fanhui(heise)"] style:UIBarButtonItemStylePlain target:self action:@selector(houtuiAction:)];
    
    
    self.button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    self.button.tintColor = [UIColor clearColor];
    self.button.frame = CGRectMake(0, 0, 25, 25);
    [self.button addTarget:self action:@selector(buttonForCollectAction:) forControlEvents:UIControlEventTouchUpInside];
    UIImage *image = [UIImage imageNamed:@"iconfont-weishoucang"];
    [self.button setBackgroundImage:[image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    
    self.buttonForCollect = [[UIBarButtonItem alloc] initWithCustomView:self.button];
    
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame = CGRectMake(0, 0, 25, 25);
    [button addTarget:self action:@selector(buttonForShareAction:) forControlEvents:UIControlEventTouchUpInside];
    UIImage *imageForShare = [UIImage imageNamed:@"iconfont-fenxiang"];
    [button setBackgroundImage:[imageForShare imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    UIBarButtonItem *buttonForShare = [[UIBarButtonItem alloc] initWithCustomView:button];
    
    self.navigationItem.rightBarButtonItems = @[buttonForShare, self.buttonForCollect];
}

- (void)buttonForCollectAction:(UIButton *)button {
    button.selected = !button.selected;
    if (button.selected) {
        
        [[DataBaseHandler shareDataBaseHandler] insertModel:self.model];
        UIImage *image = [UIImage imageNamed:@"iconfont-shoucang"];
        [button setBackgroundImage:[image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        [self presentViewController:self.alert animated:YES completion:^{
            
        }];
    } else {
        
        [[DataBaseHandler shareDataBaseHandler] deleteWithId:self.model.spot_id];
        UIImage *image = [UIImage imageNamed:@"iconfont-weishoucang"];
        [button setBackgroundImage:[image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        
    }
    
}

- (void)buttonForShareAction:(UIButton *)button {
    NSLog(@"分享");
    
    UMSocialSnsPlatform *snsPlatform4 = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToWechatTimeline];
    snsPlatform4.displayName = @"微信朋友圈";
    
    UMSocialSnsPlatform *snsPlatform5 = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToQQ];
    snsPlatform5.displayName = @"QQ";
    
    ModelForSectionHeader *modelForHeader = [self.arrForSectionHeader lastObject];
    
    UIImageView *imageView = [[UIImageView alloc] init];
    [imageView sd_setImageWithURL:[NSURL URLWithString:modelForHeader.photo_s]];
    NSString *text = [NSString stringWithFormat:@"快来看看我的分享: http://web.breadtrip.com/%@",modelForHeader.share_url];
    
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"56d10927e0f55a08e7002f24"
                                      shareText:text
                                     shareImage:imageView.image
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToWechatTimeline,UMShareToQQ,nil]
                                       delegate:nil];
    //UMShareToSina(新浪微博)
    //UMShareToWechatTimeline(微信朋友圈)
    //UMShareToQQ(qq)
}

- (void)houtuiAction:(UIBarButtonItem *)item {
    [self.navigationController popViewControllerAnimated:YES];
    self.tabBarController.tabBar.hidden = NO;
    
}

- (void)createTableView {
    
    self.tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStyleGrouped];
    self.tableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.tableView];
    [_tableView release];
   
    
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    // 注册区头部
    [self.tableView registerClass:[ViewForSectionHeader class] forHeaderFooterViewReuseIdentifier:@"poolForHeader"];
    [self.tableView registerClass:[CellForClickItem class] forCellReuseIdentifier:@"pool"];
    // 注册区尾部
    [self.tableView registerClass:[ViewForSectionFooter class] forHeaderFooterViewReuseIdentifier:@"poolForFooter"];
    
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.arrForClickItem.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
 
    
    ModelForClickItem *model = [self.arrForClickItem objectAtIndex:indexPath.row];
    CGFloat labelFloat = [NSString heightForLabel:model.text withWidth:self.view.frame.size.width - 40 withEdge:0 withFontOfSize:13];
    CGFloat scale = model.photo_height.floatValue / model.photo_width.floatValue;
    return scale * (self.view.bounds.size.width - 40) + 5 + labelFloat + 10 + 20;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    ModelForSectionHeader *model = [self.arrForSectionHeader lastObject];
    
    CGFloat height = [NSString heightForLabel:model.text withWidth:[UIScreen mainScreen].bounds.size.width - 40 withEdge:0 withFontOfSize:17];
    
    return 20 + 50 + 20 + 1 + height + 20 + 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    ViewForSectionHeader *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"poolForHeader"];
    view.contentView.backgroundColor = [UIColor clearColor];
    [view passData:[self.arrForSectionHeader lastObject]];
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return 90;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    ViewForSectionFooter *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"poolForFooter"];
    view.contentView.backgroundColor = [UIColor clearColor];
    ModelForSectionFooter *model = [self.arrForSectionFooter lastObject];
    [view passData:model];
    return view;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ModelForClickItem *model = [self.arrForClickItem objectAtIndex:indexPath.row];
    CellForClickItem *cell = [tableView dequeueReusableCellWithIdentifier:@"pool"];
    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell passData:model];
    return cell;
}

- (void)handleData {
    self.arrForSectionHeader = [NSMutableArray array];
    self.arrForClickItem = [NSMutableArray array];
    self.arrForSectionFooter = [NSMutableArray array];
    
    [NetWorkHandler networkingWithUrl:self.spot_id comleteHandle:^(id result, NSData *data) {
        
        NSDictionary *dataDic = [result objectForKey:@"data"];
        
        NSMutableArray *arr = [NSMutableArray array];
        [arr addObject:[dataDic objectForKey:@"spot"]];
        [arr addObject:[dataDic objectForKey:@"trip"]];
        
        ModelForSectionHeader *modelForHeader = [[ModelForSectionHeader alloc] init];
        /*********************解析区头数据**********************/
        for (NSDictionary *dic in arr) {
            [modelForHeader setValuesForKeysWithDictionary:dic];
        }
        [self.arrForSectionHeader addObject:modelForHeader];
        [modelForHeader release];
        /*********************解析区尾数据**********************/
        NSDictionary *dicForFooter = [arr firstObject];
        ModelForSectionFooter *modelForFooter = [[ModelForSectionFooter alloc] init];
        [modelForFooter setValuesForKeysWithDictionary:dicForFooter];
        [self.arrForSectionFooter addObject:modelForFooter];
        [modelForFooter release];
        /*********************解析row数据**********************/
        NSDictionary *tempDic = [arr firstObject];
        NSArray *tempArr = [tempDic objectForKey:@"detail_list"];
        for (NSDictionary *dic in tempArr) {
            ModelForClickItem *model = [[ModelForClickItem alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            
            NSMutableString *str = [NSMutableString stringWithString:model.photo_s];
            [str deleteCharactersInRange:[str rangeOfString:@"?imageView/1/w/280/h/280/q/75"]];
            model.photo_s = str;
            [self.arrForClickItem addObject:model];
            [model release];
        }
        
        [self.tableView reloadData];
        [[UIViewForActivityIndicator shareActivityIndicatorViewWithFrame:self.view.frame] didFinishLoad];
        
    }];
    
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
